//
//  SSNormalDetailController.swift
//  拾舍清洁
//
//  Created by sky.wei on 2023/6/1.
//

import UIKit


class SSNormalDetailController: UIViewController {
    //回调
    var callback:SSCallBack = {}
    //详情信息
    var normal = SSNormal()
    //服务内容
    var listContentImg = [SSNormal]()
    //说明
    var listTextImg = [SSNormal]()
    //总图片数组
    var totalList = [SSNormal]()
    
    //总折叠数据
    var totalFolds = [SSFoldModel]()
    
    var serviceType:Int = 0//0、单次 1、套餐 2、宠物
    var serviceIndex = 1
    var serviceBenefitIndex = 6
    var qaIndex = 7
    var titles = [String]()
    var texts = [String]()

    @IBOutlet weak var tableView: UITableView!
    @IBOutlet weak var segmentView: SSSegmentView!
    var headerview = SSNormalDetailHeader()
//    var segmentView = SSSegmentView()
    
  

  
    override func viewDidLoad() {
        super.viewDidLoad()
        
        title = "商品详情"
        let nv = self.navigationController as! NavigationController
        nv.callback {
            self.callback()
        }
        
        //选择器
        segmentView.setupUI2()
        segmentView.mealResult { index in
            print("\(index)")
            print("")
            if(index == 0){
                self.tableView.selectRow(at: IndexPath(row: 0, section: 0), animated: true, scrollPosition: .top)
            }else if(index == 1){
                self.tableView.selectRow(at: IndexPath(row: 1, section: 0), animated: true, scrollPosition: .top)
            }else if(index == 2){
                self.tableView.selectRow(at: IndexPath(row: 0, section: 1), animated: true, scrollPosition: .top)
            }
        }
        
        //MARK: 折叠处理数据
        serviceType = normal.type
        serviceIndex = 1
        serviceBenefitIndex = 6
        getText()
        for (index,title) in titles.enumerated(){
            let m = SSFoldModel()
            m.title = title
            m.isfold = false
            m.text = texts[index]
            m.height = m.text.sizeWithText(font: UIFont.systemFont(ofSize: 14), size: CGSize(width: ScreenWidth - 12 * 2, height: CGFloat.zero)).height + 20
            totalFolds.append(m)
        }
        
        //界面
        setupUIS()
        //网络
        getDayItemDetail()

    }
    
    
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        headerview.frame = CGRect(x: 0, y: 0, width: ScreenWidth, height: 590 + 40 + 20)
    }
    
    
    

    func callback(_ finished: @escaping SSCallBack) {
        callback = finished
    }

    
}


//MARK: 点击事件
extension SSNormalDetailController {
    
    @IBAction func bugAction(_ sender: Any) {
        print("111")
        let vc = SSNormalUserOrderController()
        vc.normal = self.normal
        self.navigationController?.pushViewController(vc, animated: true)
    }
    
    @IBAction func contantAction(_ sender: Any) {
        enterMeiqia()
    }
    
    
    @objc func foldAction(_ btn:UIButton){
        
        let index:Int = btn.tag
        if(index == serviceIndex || index == qaIndex){
            return
        }
        
        self.totalFolds[btn.tag - 1].isfold = !self.totalFolds[btn.tag - 1].isfold
        self.tableView.reloadSections(NSIndexSet(index: btn.tag) as IndexSet, with: UITableView.RowAnimation.none)
    }

}

//MARK: table代理
extension SSNormalDetailController: UITableViewDelegate, UITableViewDataSource
{
    func setupContentOffset(y:Double) {
        print("----contentOffset.y:\(y)")
        var index = 0
        if(y < 602){
            index = 0
        }
        if(y > 1189 && y < 5781){
            index = 1
        }
        if(y > 5781){
            index = 2
        }
        self.segmentView.setupSelectedItem2(index: index)
    }
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        setupContentOffset(y: scrollView.contentOffset.y)
//        print("----contentOffset.y:\(scrollView.contentOffset.y)")
    }
    
    func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
        setupContentOffset(y: scrollView.contentOffset.y)
//        print("----DraggingcontentOffset.y:\(scrollView.contentOffset.y)")
    }
    
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1 + totalFolds.count
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        if(section == serviceIndex){//服务规则
            return 1
        }
        if(section == qaIndex){//qa
            return 0
        }
        
        if(section < 1){
            return self.totalList.count
        }
        let m = self.totalFolds[section - 1]
        if(m.isfold){
            return 1
        }
        
        return 0
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if(indexPath.section == 0){
            let cell = tableView.dequeueReusableCell(withIdentifier: "SSNormalDetaillCell") as! SSNormalDetaillCell
            cell.normal = totalList[indexPath.row]
            return cell
        }
        
        if(indexPath.section == serviceIndex){//服务规则
            let cell = tableView.dequeueReusableCell(withIdentifier: "cell")!
            return cell
        }
        
        if(indexPath.section == 2){
            let cell = tableView.dequeueReusableCell(withIdentifier: "SSPrePurchaseNoticeCell") as! SSPrePurchaseNoticeCell
            return cell
        }else if (indexPath.section == 3){
            let cell = tableView.dequeueReusableCell(withIdentifier: "SSTempCancelCell") as! SSTempCancelCell
            return cell
        }
        else if (indexPath.section == 6){
            let cell = tableView.dequeueReusableCell(withIdentifier: "SSServiceBenefitCell") as! SSServiceBenefitCell
            return cell
        }
        let cell = tableView.dequeueReusableCell(withIdentifier: "SSNormalTextCell") as! SSNormalTextCell
        cell.textLab.text = self.totalFolds[indexPath.section - 1].text
        return cell
    
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if(indexPath.section < 1){
            return getNormalDetailImageH()
        }
        if(indexPath.section == serviceIndex){
            return 0.01
        }
        if(indexPath.section == 2){
            return 510
        }else if (indexPath.section == 3){
            return 370
        }
        else if (indexPath.section == 6){
            return 260
        }
        else {
            return self.totalFolds[indexPath.section - 1].height
        }
        return 40
    }
    

    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        if(section < 1){
            return 0.01
        }
        return 56
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0.01
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        
        if(section < 1){
            return UIView()
        }
        let bgview = UIView(frame: CGRect(x: 0, y: 0, width: ScreenWidth, height: 56))
        bgview.backgroundColor = UIColor.white
        let btn = UIButton(frame: CGRect(x: 12, y: 0, width: bgview.frame.width - 12 * 2, height: bgview.frame.height))
        btn.addTarget(self, action: #selector(foldAction(_:)), for: .touchUpInside)
        btn.titleLabel?.font = UIFont.systemFont(ofSize: 18)
        btn.contentHorizontalAlignment = .left
//        btn.backgroundColor = UIColor.blue
        btn.tag = section
        btn.setTitleColor(UIColor.black, for: .normal)
        btn.setTitle(self.totalFolds[section - 1].title, for: .normal)
        bgview.addSubview(btn)
        
        
        let line = UIView(frame: CGRect(x: 12, y: bgview.frame.height - 2, width: btn.frame.width, height: 1))
        line.backgroundColor = UIColor.systemGray3
        bgview.addSubview(line)
        
        if(section == serviceIndex || section == qaIndex){
            btn.setTitleColor(UIColor(hex: "4579B3"), for: .normal)
        }else{
            btn.setTitleColor(UIColor.black, for: .normal)
            let foldIcon = UIImageView(frame: CGRect(x: Int(bgview.frame.width) - 44, y: (Int(bgview.frame.height) - 20)/2, width: 25, height: 20))
            let m = self.totalFolds[section - 1]
            if(m.isfold){
                foldIcon.image = UIImage(named: "reduce")
                line.backgroundColor = UIColor(hex: "4579B3")
            }else{
                foldIcon.image = UIImage(named: "add")
                line.backgroundColor = UIColor.systemGray3
            }
            bgview.addSubview(foldIcon)

        }
        return bgview
}
  
}

//MARK: 网络
extension SSNormalDetailController {
    
    //banner
    func getDayItemDetail() {
        let param = [
            "id": normal.pkgId
        ]as[String:AnyObject]
        SSNetwrokManager.share.request(urlString: APIUrl.share.getDayItemDetail_URL,
                                       parameters:param) { result in
            debugPrint("")
            
            guard let listTextImg = [SSNormal].deserialize(from: result, designatedPath:"data.listTextImg") else {
                return
            }
            self.listTextImg = listTextImg as! [SSNormal]
            
            guard let listContentImg = [SSNormal].deserialize(from: result, designatedPath:"data.listContentImg") else {
                return
            }
            self.listContentImg = listContentImg as! [SSNormal]

            self.totalList = self.totalList + self.listContentImg + self.listTextImg
            self.tableView.reloadData()
            print("")
        }
    }
}









        
